package com.peng.community.controller;

import com.peng.community.constant.CommunityConstant;
import com.peng.community.entity.Event;
import com.peng.community.entity.User;
import com.peng.community.event.EventProducer;
import com.peng.community.service.impl.LikeService;
import com.peng.community.util.CommunityUtils;
import com.peng.community.util.HostHolder;
import com.peng.community.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
public class LikeController implements CommunityConstant {

    @Autowired
    LikeService likeService;

    @Autowired
    HostHolder hostHolder;

    @Autowired
    EventProducer eventProducer;

    @Autowired
    RedisTemplate redisTemplate;

    @PostMapping("/like")
    @ResponseBody //异步请求
    public String like(int entityType, int entityId, int entityUserId, int postId) {
        User user = hostHolder.getUser();
        likeService.like(user.getId(), entityType, entityId, entityUserId);

        Long entityLikeCount = likeService.findEntityLikeCount(entityType, entityId);
        int likeStatus = likeService.findEntityLikeStatus(user.getId(), entityType, entityId);

        Map<String, Object> map = new HashMap<>();
        map.put("likeCount", entityLikeCount);
        map.put("likeStatus",likeStatus);

        if (likeStatus == 1) {
            //点赞才对主人发通知
            Event event = new Event()
                    .setEntityId(entityId)
                    .setUserId(user.getId())
                    .setTopic(TOPIC_LIKE)
                    .setEntityUserId(entityUserId)
                    .setEntityType(entityType)
                    .setData("postIdD" , postId);
            eventProducer.send(event);
        }

        if (entityType == ENTITY_TYPE_POST) {
            //若评论的是帖子，为帖子增加热度评分
            String postScoreKey = RedisKeyUtil.getPostScoreKey();
            redisTemplate.opsForSet().add(postScoreKey, postId);
        }

        return CommunityUtils.toJsonString(0, null, map);
    }
}
